<!-- 游戏RTP调控 -->
<template>
  <SearchTable ref="SearchTableRef" :query="data.query" :list="data.list" :total="data.total" @changeSize="changeSize"
    @changePage="changePage" @search="getSearchList" @reset="resetDetails" @changeTh="data.dialogVisible = true" :showSet="false">
    <template #other>
      <el-tabs v-model="data.nameType" type="card" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="游戏RTP调控功能" :name="1" />
        <el-tab-pane label="养客机制点控" :name="2" />
      </el-tabs>
    </template>
    <template #form>
      <Operator ref="OperatorRef" @query="queryItem" />
      <el-form-item label="" v-if="data.nameType == 2 ? true:false">
        <el-select class="selectWidth120" v-model="data.query.search_type" placeholder="请选择">
          <el-option v-for="item in data.conditionList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input class="width200" v-model="data.query.search_value" placeholder="请输入" clearable
          onKeyUp="value=value.replace(/[\W]/g,'')" />
      </el-form-item>
      <el-form-item label="控制时间：" v-if="data.nameType == 2 ? true:false">
        <el-date-picker v-model="data.query.date" type="daterange" range-separator="-" start-placeholder="请选择开始时间"
          end-placeholder="请选择结束时间" value-format="YYYY-MM-DD" clearable :disabled-date="indexStore.disabledDateTime"/>
      </el-form-item>
    </template>
    <template #button>
      <el-button v-if="(!indexStore.is_general_agent && data.nameType == 1) ? true : false" type="danger"
        v-permiss="'/system/destroyManager'" size="small" @click="data.isShowCommercial = true">
        功能状态批量控制
      </el-button>
      <el-button v-if="(!indexStore.is_general_agent && data.nameType == 1) ? true : false" type="warning"
        v-permiss="'/system/destroyManager'" size="small" @click="getInitializeRTP()">
        商户功能表初始化
      </el-button>
      <el-button v-if="(!indexStore.is_general_agent && data.nameType == 1) ? true : false" type="danger"
        v-permiss="'/system/destroyManager'" size="small" @click="data.isShowRTP = true">
        商户功能表同步商户
      </el-button>
      <div class="tipsTextRed marginL10 marginT5" v-if="(!indexStore.is_general_agent && data.nameType == 1) ? true : false">
        <p>此功能分为两部分：一部分为控制所有玩家进入游戏时的提升状态（高RTP提升玩家游戏感受），当玩家达到设定值（盈利/流水倍数）后功能关闭，此玩家不再受功能提升控制；相关配置为“编辑”按钮内的“养客机制配置”。</p>
        <p>另一部分为控制新账号新玩家进入游戏的新手体验过程保护机制，增强新玩家对游戏的初始体验，提升游戏时长；相关配置点击“编辑”按钮查看、设定。</p>
        <p>两部分功能出发点及逻辑互不干扰，可并用触发。若不需要此功能可点击“功能开关控制”进行关闭。</p>
      </div>
      <el-button v-if="(data.nameType == 2) ? true : false" type="danger"
        v-permiss="'/system/destroyManager'" size="small" @click="getDefaultInfo">
        新增玩家控制
      </el-button>
    </template>
    <template #table>
      <template v-for="(item, index) in data.fields" :key="index">
        <el-table-column :prop="item.prop" :label="item.label" :width="item.width">
          <template #header>
            <el-tooltip v-if="item.tips" effect="dark" placement="top">
              <template #content>
                {{ item.tips }}
              </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            {{ item.label }}
          </template>
          <template v-if="item.prop == 'save_time_stamp'" #default="scope">
            {{ setTimestampTime(scope.row.save_time_stamp) }}
          </template>
          <template v-if="item.prop == 'agent_id'" #default="scope">
            {{ selectToLabel(indexStore.agentArray, scope.row.agent_id) }}
          </template>
          <template v-if="item.prop == 'a_slots_pigCycle'" #default="scope">
            {{ selectToLabel(data.cycleList, Number(scope.row.a_slots_pigCycle)) }}
          </template>
        </el-table-column>
      </template>
      <el-table-column label="养客机制" v-if="data.nameType == 1 ? true : false">
        <template v-for="(item, index) in data.fieldsFosterer" :key="index">
          <el-table-column :prop="item.prop" :label="item.label" :width="item.width" header-row-class-name="fosterer">
            <template #header>
              <el-tooltip v-if="item.tips" effect="dark" placement="top">
                <template #content>
                  {{ item.tips }}
                </template>
                <el-icon class="ques-tips">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
              {{ item.label }}
            </template>
            <template v-if="item.prop == 'player_state'" #default="scope">
              <el-tag type="success">{{ scope.row.player_state }}</el-tag>
            </template>
            <template v-if="item.prop == 'a_slots_pigNumber'" #default="scope">
              {{ selectToLabel(data.cycleList, Number(scope.row.a_slots_pigCycle)) + scope.row.a_slots_pigNumber }}次
            </template>
          </el-table-column>
        </template>
      </el-table-column>
      <el-table-column label="调控功能" v-if="data.nameType == 1 ? true : false">
        <template v-for="(item, index) in data.fieldsProtection" :key="index">
          <el-table-column :prop="item.prop" :label="item.label" :width="item.width">
            <template #header>
              <el-tooltip v-if="item.tips" effect="dark" placement="top">
                <template #content>
                  {{ item.tips }}
                </template>
                <el-icon class="ques-tips">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
              {{ item.label }}
            </template>
            <template v-if="item.prop == 'rtp_help'" #default="scope">
              {{ scope.row.beginner }} / {{ scope.row.nobeginner }}
            </template>
            <template v-if="item.prop == 'rtp_radio'" #default="scope">
              {{ scope.row.rtp_radio }}%
            </template>
            <template v-if="item.prop == 'a_slots_protectopen'" #default="scope">
              <el-tag :type="scope.row.a_slots_protectopen ? 'success' : 'danger'">{{ selectToLabel(DEMOPLAY,
                scope.row.a_slots_protectopen) }}</el-tag>
            </template>
            <template v-if="item.prop == 'rtp_control'" #default="scope">
              <el-tooltip effect="dark" placement="bottom">
                <template #content>
                  <div class="width500">
                    <span class="marginR5" v-for="(second, two) in scope.row.rtp_control" :key="two">
                      档位<span class="colorRed">{{ second.gear }}</span>,
                      降低幅度<span class="colorRed">{{ second.drop }}%</span>,
                      拉回幅度<span class="colorRed">{{ second.pull }}%</span>,
                      新手概率<span class="colorRed">{{ second.beginner }}%</span>,
                      非新手概率<span class="colorRed">{{ second.nobeginner }}%</span>
                      <span>,触发区间上下限<span class="colorRed">{{ second.lowerMin }}% ~ 上限{{ second.lowerMax
                          }}%</span>,</span>
                      <span>提升后上下限<span class="colorRed">{{ second.upperMin }}% ~ 上限{{ second.upperMax
                          }}%</span></span>；
                      <pre />
                    </span>
                  </div>
                </template>
                <div class="text-cut">
                  <span class="marginR5" v-for="(second, two) in scope.row.rtp_control" :key="two">
                    档位<span class="colorRed">{{ second.gear }}</span>,
                    降低幅度<span class="colorRed">{{ second.drop }}%</span>,
                    拉回幅度<span class="colorRed">{{ second.pull }}%</span>,
                    新手概率<span class="colorRed">{{ second.beginner }}%</span>,
                    非新手概率<span class="colorRed">{{ second.nobeginner }}%</span>
                    <span v-show="second.lowerMin && second.lowerMax">,触发区间上下限<span class="colorRed">{{ second.lowerMin
                        }}% ~ 上限{{
                        second.lowerMax }}%</span>,</span>
                    <span v-show="second.lowerMin && second.lowerMax">提升后上下限<span class="colorRed">{{ second.upperMin
                        }}% ~ 上限{{
                        second.upperMax }}%</span></span>；
                  </span>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120" align="center">
        <template #header>
          <el-tooltip effect="dark" content="点击按钮进行编辑参数" placement="top">
            <el-icon class="ques-tips">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
          编辑
        </template>
        <template #default="scope">
          <el-button type="warning" v-if="data.nameType==1?true:false" v-permiss="'/system/destroyManager'" size="small" @click="checkDetails(scope.row)">
            编 辑
          </el-button>
          <el-button type="danger" v-else v-permiss="'/system/destroyManager'" size="small" @click="deleteUserControl(scope.row)">
            解除点控
          </el-button>
        </template>
      </el-table-column>
    </template>
  </SearchTable>

  <!-- 变更表头弹框 -->
  <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
    @resetData="resetData"></tableHeader>

  <!-- RTP同步商户 -->
  <el-dialog v-model="data.isShowRTP" title="RTP同步商户" :close-on-click-modal="false" :close-on-press-escape="false"
    width="50%" top="25vh" @close="data.isShowRTP = false">
    <MultipleOperator ref="BatchControlRTPRef"></MultipleOperator>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" @click="data.isShowRTP = false">取 消</el-button>
        <el-button type="primary" @click="getSynchronizationRTP()">确 定</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 功能开关控制 -->
  <el-dialog v-model="data.isShowCommercial" title="功能开关批量控制" :close-on-click-modal="false"
    :close-on-press-escape="false" width="50%" top="25vh" @close="data.isShowCommercial = false">
    <MultipleOperator ref="BatchControlRef">
      <template #footer>
        <form-item title="功能状态" :pass="true" value="a_slots_protectopen">
          <el-radio-group v-model="data.commercialForm.a_slots_protectopen" size="large">
            <el-radio-button label="关闭" :value="0" />
            <el-radio-button label="开启" :value="1" />
          </el-radio-group>
        </form-item>
      </template>
    </MultipleOperator>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" @click="data.isShowCommercial = false">取 消</el-button>
        <el-button type="primary" @click="initialSynchronization">确 定</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 调控配置 -->
  <el-dialog v-model="data.isShowDetails" title="保护配置" :close-on-click-modal="false" :close-on-press-escape="false"
    :destroy-on-close="true" width="50%" :top="!indexStore.is_general_agent ? '8vh' : '10vh'" @close="data.isShowDetails = false">
    <template #header>
      <p class="box-title mustPass">【{{ data.formParams.agent_id }}】{{ data.formParams.agent_name }}</p>
    </template>
    <div v-loading="indexStore.moduleLoading" class="dialogMaxHeight">
      <el-form ref="ruleFormRef" :model="data.formParams" :inline="true" :rules="data.rules" :scroll-to-error="true">
        <form-item title="新手局数" :pass="true" value="rtp_num">
          <el-input-number v-model="data.formParams.rtp_num" :min="0" :max="99999999999999999999" :precision="0"
            placeholder="新手局数" clearable controls-position="right" />
          <span class="tipsText">(玩家生涯的游戏局数，在此局数范围内为新手玩家，反之为非新手玩家)</span>
        </form-item>
        <form-item title="新手救助次数" :pass="true" value="beginner" v-if="!indexStore.is_general_agent">
          <el-input-number v-model="data.formParams.beginner" :min="0" :max="99999999999999999999" :precision="0"
            placeholder="新手救助次数" clearable controls-position="right" />
          <span class="tipsText">(设定新手玩家提升RTP功能的历史触发次数)</span><span v-if="indexStore.is_general_agent">%</span>
        </form-item>
        <form-item title="非新手救助次数" :pass="true" value="nobeginner" v-if="!indexStore.is_general_agent">
          <el-input-number v-model="data.formParams.nobeginner" :min="0" :max="99999999999999999999" :precision="0"
            placeholder="非新手救助次数" clearable controls-position="right" />
          <span class="tipsText">(设定非新手玩家提升RTP功能的历史触发次数)</span><span v-if="indexStore.is_general_agent">%</span>
        </form-item>
        <form-item title="检测局数" :pass="true" value="rtp_check" v-if="!indexStore.is_general_agent">
          <el-input-number v-model="data.formParams.rtp_check" :min="0" :max="99999999999999999999" :precision="0"
            placeholder="检测局数" clearable controls-position="right" />
          <span class="tipsText">(玩家在游戏中每隔设定局数检测当前最新RTP值)</span>
        </form-item>
        <form-item title="浮动率" :pass="true" value="rtp_radio" v-if="!indexStore.is_general_agent">
          <el-input-number v-model="data.formParams.rtp_radio" :min="0" :max="100" :precision="2" placeholder="浮动率"
            clearable controls-position="right" />%
          <span class="tipsText">(设定玩家RTP上下限的误差范围)</span>
        </form-item>
        <!-- <form-item title="调控功能状态" value="a_slots_protectopen">
          <el-radio-group v-model="data.formParams.a_slots_protectopen" size="large">
            <el-radio-button label="关闭" :value="0" />
            <el-radio-button label="开启" :value="1" />
          </el-radio-group>
        </form-item> -->
        <form-item title="养客机制配置" :pass="true" value="a_slots_pig">
          <div class="marginB5">
            达到设定盈利关闭提升状态：<el-input-number v-model="data.formParams.a_slots_pigProfit" :min="1" :max="999999999999999999"
              :precision="0" placeholder="达到设定盈利关闭提升状态" clearable controls-position="right" />
            <span class="tipsText">(设定玩家盈利值，玩家盈利达到这个值后不再提升RTP，玩家恢复正常状态)</span>
          </div>
          <div class="marginB5">
            达到设定流水倍数关闭提升状态：<el-input-number v-model="data.formParams.a_slots_pigWater" :min="1"
              :max="999999999999999999" :precision="0" placeholder="达到设定流水倍数关闭提升状态" clearable
              controls-position="right" />
            <span class="tipsText">(设定玩家流水倍数值，玩家游戏中的流水倍数达到这个值后不再提升RTP，玩家恢复正常状态)</span>
          </div>
          <div class="marginB5">
            触发周期选择：<el-select class="marginR10" v-model="data.formParams.a_slots_pigCycle" placeholder="请选择" filterable
              @change="chooseCycle">
              <el-option v-for="item in data.cycleList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            触发次数：<el-input-number v-model="data.formParams.a_slots_pigNumber" :min="1" :max="999999999999999999"
              :precision="0" placeholder="触发次数" clearable controls-position="right" />
            <span class="tipsText">(设定此功能对玩家RTP提升控制的触发周期,设定玩家在“触发周期”内可被功能控制的次数)</span>
            <div v-if="data.formParams.a_slots_pigCycle == 5 ? true : false">
              自定义周期：<el-date-picker v-model="data.formParams.date" type="datetimerange" range-separator="-"
                start-placeholder="请选择开始时间" end-placeholder="请选择结束时间" value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="indexStore.disabledBeforeDateTime" />
            </div>
          </div>
          <div class="marginB5">
            触发间隔局数：<el-input-number v-model="data.formParams.a_slots_pigInning" :min="1" :max="999999999999999999"
              :precision="0" placeholder="触发间隔局数" clearable controls-position="right" />
            <span class="tipsText">(玩家功能生效控制后，冷却局数，需达到此局数后可再被控制)</span>
          </div>
        </form-item>
        <form-item title="保护配置" :pass="true" value="rtp_control" :subtract="true" @addItem="addControl">
          <span class="tipsText"><span class="tipsTextRed">新手被救助概率</span> ：设定新手玩家RTP在触发区间内被调控的概率；</span>
          <span class="tipsText"><span class="tipsTextRed">非新手救助概率</span>：设定非新手玩家RTP在触发区间内被调控的概率；</span>
          <div class="flexWrap marginT5" v-for="(item, index) in data.formParams.rtp_control" :key="index">
            档位: <el-input-number v-model="item.gear" :min="0" :max="99999999999999999999" :precision="0"
              class="width120 marginR10 marginL5" placeholder="档位" clearable :controls="false" />
            <p v-if="!indexStore.is_general_agent">
              降低幅度:<el-input-number v-model="item.drop" :min="0" :max="100" :precision="2" class="width150 marginL5"
                placeholder="降低幅度" clearable :controls="false" />%
            </p>
            <p class="marginL10" v-if="!indexStore.is_general_agent">
              拉回幅度:<el-input-number v-model="item.pull" :min="0" :max="100" :precision="2" class="width150"
                placeholder="拉回幅度" clearable :controls="false" v-if="!indexStore.is_general_agent" />%
            </p>
            新手概率:<el-input-number v-model="item.beginner" :min="0" :max="100" :precision="0"
              class="width150 marginL20 marginT5 " placeholder="新手概率" clearable :controls="false" /><span
              class="marginR10">%</span>
            非新手概率:<el-input-number v-model="item.nobeginner" :min="0" :max="100" :precision="0"
              class="width150 marginL5 marginT5 " placeholder="非新手概率" clearable :controls="false" />%
            <div class="reduce-btn marginL5" @click="reduceControl(index)">-</div>
          </div>
        </form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" @click="data.isShowDetails = false">取 消</el-button>
        <el-button type="primary" @click="editControl">确 定</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 新增玩家点控保护机制 -->
  <el-dialog v-model="data.isShowUserControl" title="新增玩家控制" :close-on-click-modal="false"
    :close-on-press-escape="false" :destroy-on-close="true" width="50%" top="10vh" @close="data.isShowDetails = false">
    <div v-loading="indexStore.moduleLoading" class="dialogMaxHeight">
      <el-form ref="ruleFormRef" :model="data.formParams" :inline="true" :rules="data.rules" :scroll-to-error="true">
        <BatchControl ref="BatchControlUserRef" :multipleShow="false" :brandShow="false" :gameShow="false">
          <template #footer>
            <form-item title="平台ID" :pass="true" value="insert_values">
              <el-input class="imWidth100" type="textarea" :row="8" v-model="data.formParams.insert_values"
                placeholder="平台ID" clearable />
              <span class="tipsText">(多个玩家ID用英文的,间隔)</span>
            </form-item>
            <form-item title="养客机制配置" :pass="true" value="a_slots_pig">
              <div class="marginB5">
                达到设定盈利关闭提升状态：<el-input-number v-model="data.formParams.a_slots_pigProfit" :min="1"
                  :max="999999999999999999" :precision="0" placeholder="达到设定盈利关闭提升状态" clearable
                  controls-position="right" />
                <span class="tipsText">(设定玩家盈利值，玩家盈利达到这个值后不再提升RTP，玩家恢复正常状态)</span>
              </div>
              <div class="marginB5">
                达到设定流水倍数关闭提升状态：<el-input-number v-model="data.formParams.a_slots_pigWater" :min="1"
                  :max="999999999999999999" :precision="0" placeholder="达到设定流水倍数关闭提升状态" clearable
                  controls-position="right" />
                <span class="tipsText">(设定玩家流水倍数值，玩家游戏中的流水倍数达到这个值后不再提升RTP，玩家恢复正常状态)</span>
              </div>
              <div class="marginB5">
                触发周期选择：<el-select class="marginR10" v-model="data.formParams.a_slots_pigCycle" placeholder="请选择"
                  filterable @change="chooseCycle">
                  <el-option v-for="item in data.cycleList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                触发次数：<el-input-number v-model="data.formParams.a_slots_pigNumber" :min="1" :max="999999999999999999"
                  :precision="0" placeholder="触发次数" clearable controls-position="right" />
                <span class="tipsText">(设定此功能对玩家RTP提升控制的触发周期,设定玩家在“触发周期”内可被功能控制的次数)</span>
                <div v-if="data.formParams.a_slots_pigCycle == 5 ? true : false">
                  自定义周期：<el-date-picker v-model="data.formParams.date" type="datetimerange" range-separator="-"
                    start-placeholder="请选择开始时间" end-placeholder="请选择结束时间" value-format="YYYY-MM-DD HH:mm:ss"
                    :disabled-date="indexStore.disabledBeforeDateTime" />
                </div>
              </div>
              <div class="marginB5">
                触发间隔局数：<el-input-number v-model="data.formParams.a_slots_pigInning" :min="1" :max="999999999999999999"
                  :precision="0" placeholder="触发间隔局数" clearable controls-position="right" />
                <span class="tipsText">(玩家功能生效控制后，冷却局数，需达到此局数后可再被控制)</span>
              </div>
            </form-item>
          </template>
        </BatchControl>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" @click="data.isShowUserControl = false">取 消</el-button>
        <el-button type="primary" @click="setUserControl">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Operator, { type QueryType } from '@/components/FormItem/Operator.vue'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import BatchControl from '@/components/FormItem/BatchControl.vue'
import MultipleOperator from '@/components/FormItem/MultipleOperator.vue'
import { DEMOPLAY } from '@/config/eunm'
import { Time } from '@/utils/serverTime'
import { setTimestampTime, setTimeValue, getSevenWeek } from '@/utils/time'
import { throttle, selectToLabel, setSemicolonToArr, setCommaToArr, setArrStr } from '@/utils/index'
import { BigHundred, BigTimeHundred } from '@/utils/math'
import { 
  getRTP, 
  editRTP, 
  initializeRTP, 
  coverRTP, 
  getUserControl, 
  addUserControl, 
  editProtectOpen, 
  delUserControl,
  getDefaultControl
} from '@/api/game'

import { useStore } from '@/stores/index'
const indexStore = useStore()

const data = reactive({
  type: 1,
  query: {
    page: 1,
    size: 50,
    agent_id: -1,
    operated_id: -1,
    search_type: 1,
    search_value: '',
    date: getSevenWeek()
  },
  list: [],
  total: 0,
  nameType: 1,
  fields: [
    { label: '上级渠道', prop: 'operator_name', width: '150', tips: '商户的上级代理' },
    { label: '商户昵称', prop: 'agent_name', width: '150', tips: '商户的名称' },
  ],
  fieldsFosterer: [
    { label: '玩家初始状态', prop: 'player_state', width: '155', tips: '玩家初始进入游戏时的RTP控制状态' },
    { label: '状态关闭盈利值', prop: 'a_slots_pigProfit', width: '120', tips: '玩家盈利值达到设定值后，此功能对玩家进行关闭，不再控制' },
    { label: '状态关闭流水倍数', prop: 'a_slots_pigWater', width: '120', tips: '玩家流水倍数达到设定值后，此功能对玩家进行关闭，不再控制' },
    { label: '触发周期', prop: 'a_slots_pigNumber', width: '150', tips: '此功能对玩家RTP提升控制的生效周期及周期内控制次数' },
    { label: '触发间隔局数', prop: 'a_slots_pigInning', width: '150', tips: '每次控制的间隔局数，控制生效后未达到此游戏局数不能再次被控制' },
  ],
  fieldsProtection: [
    { label: '功能状态', prop: 'a_slots_protectopen', width: '120', tips: '此商户的此功能状态显示' },
    { label: '新手局数', prop: 'rtp_num', width: '120', tips: '玩家生涯的游戏局数，在此局数范围内为新手玩家，反之为非新手玩家' },
    { label: '新手/非新手救助次数', prop: 'rtp_help', width: '120', tips: '新手玩家/非新手玩家提升RTP功能的历史触发次数' },
    { label: '检测局数', prop: 'rtp_check', width: '120', tips: '玩家在游戏中每隔设定局数检测当前最新RTP值' },
    { label: '浮动率', prop: 'rtp_radio', width: '100', tips: '玩家RTP上下限的误差范围' },
    { label: '保护配置', prop: 'rtp_control', width: '240', tips: '所有档位配置说明及触发区间和提升结果' },
  ],
  conditionList: [
    { label: '平台ID', value: 1 },
    { label: '平台昵称', value: 3 }
  ],
  dialogVisible: false,
  isShowDetails: false,
  isShowUserControl: false,
  isShowCommercial: false,
  isShowRTP: false,
  commercialForm: {
    agent_ids: [],
    game_ids: [],
    a_slots_protectopen: 0,
  },
  commercialArray: [] as any[],
  controlList: [] as any[],
  whiteList: [] as any[],
  formParams: {
    rtp_num: 0,
    beginner: 0,
    nobeginner: 0,
    rtp_check: 0,
    rtp_radio: 0,
    rtp_control: [] as any[],
    a_slots_pigProfit: 0,
    a_slots_pigWater: 0,
    a_slots_pigNumber: 1,
    a_slots_pigCycle: 1,
    pigCycle: 0,
    a_slots_pigInning: 0,
    date: [],
    insert_values: ''
  } as any,
  rules: {
    rtp_num: [{ required: true, message: '请输入新手局数', trigger: 'blur' }],
    beginner: [{ required: true, message: '请输入新手救助次数', trigger: 'blur' }],
    nobeginner: [{ required: true, message: '请输入非新手救助次数', trigger: 'blur' }],
    rtp_check: [{ required: true, message: '请输入检测局数', trigger: 'blur' }],
    rtp_radio: [{ required: true, message: '请输入浮动率', trigger: 'blur' }],
  },
  cycleList: [
    { label: '每日', value: 1 },
    { label: '每周', value: 2 },
    { label: '每月', value: 3 },
    { label: '终生', value: 4 },
    { label: '自定义周期', value: 5 },
  ]
})

// 商户类别 + 商户
const queryItem = (item: QueryType) => {
  data.query.agent_id = item.agent_id
  data.query.operated_id = item.operated_id
}

onMounted(async () => {
  getSearchList()
})

const getSearchList = async () => {
  indexStore.setPageLoading(true)
  let query = JSON.parse(JSON.stringify(data.query));
  query = setTimeValue(query)
  let res = data.nameType ==1 ? await getRTP(query) : await getUserControl(query)
  res.data?.list?.forEach((item: any) => {
    item.player_state = '提升'
    let slotsPig = setCommaToArr(item.a_slots_pig)
    item.a_slots_pigCycle = Number(slotsPig[0]) // 周期
    item.pigCycle = Number(slotsPig[0]) // 周期
    item.a_slots_pigWater = Number(slotsPig[1]) //流水倍数
    item.a_slots_pigProfit = Number(slotsPig[2]) //玩家净盈利
    item.a_slots_pigNumber = Number(slotsPig[3]) //生效次数
    item.a_slots_pigInning = Number(slotsPig[4]) //局数CD
    // 自定义周期开始结束时间
    if (item.a_slots_pigCycle == 5) {
      item.date = [setTimestampTime(Number(slotsPig[5])), setTimestampTime(Number(slotsPig[6]))]
    } else {
      item.date = []
    }
    if( data.nameType ==1){
      item.a_slots_protect_arr.forEach((second: any, index: number) => {
        // 新手局数
        if (index == 0) item.rtp_num = Number(second)
        // 新手救助次数
        if (index == 1) item.beginner = Number(setCommaToArr(second)[0])
        // 非新手救助次数
        if (index == 1) item.nobeginner = Number(setCommaToArr(second)[1])
        // 检测执行局数
        if (index == 2) item.rtp_check = Number(second)
        // 浮动率
        if (index == 3) item.rtp_radio = BigHundred(second)
        // 保护配置
        if (index == 4) item.rtp_control = setArrControl(second, item.lower_max, item.lower_min, item.upper_max, item.upper_min)
      })
    }
  })
  data.list = res.data.list
  data.total = res.data.total
}

// 选择游戏tab
const SearchTableRef = ref<any>()
const handleClick = async (value: any) => {
  data.list = []
  data.total = 0
  data.nameType = value.paneName
  SearchTableRef.value.initTableMaxHeight()
  if(value.paneName==1){
    data.fields = [
      { label: '上级渠道', prop: 'operator_name', width: '150', tips: '商户的上级代理' },
      { label: '商户昵称', prop: 'agent_name', width: '150', tips: '商户的名称' },
    ]
  }else{
    data.fields = [
      { label: '控制时间', prop: 'save_time_stamp', width: '170', tips: '玩家的控制时间' },
      { label: '商户昵称', prop: 'agent_id', width: '150', tips: '玩家所属商户' },
      { label: '平台ID', prop: 'account3d_id', width: '120', tips: '玩家ID编号，唯一' },
      { label: '平台昵称', prop: 'account3d', width: '180', tips: '玩家名称' },
      { label: '设定盈利值', prop: 'a_slots_pigProfit', width: '', tips: '玩家盈利达到这个值后不再提升RTP，玩家恢复正常状态' },
      { label: '设定流水倍数', prop: 'a_slots_pigWater', width: '', tips: '玩家游戏中的流水倍数达到这个值后不再提升RTP，玩家恢复正常状态' },
      { label: '触发周期', prop: 'a_slots_pigCycle', width: '120', tips: '玩家RTP提升控制的触发周期' },
      { label: '触发次数', prop: 'a_slots_pigNumber', width: '', tips: '设定玩家在“触发周期”内可被功能控制的次数' },
      { label: '触发间隔局数', prop: 'a_slots_pigInning', width: '', tips: '玩家功能生效控制后，冷却局数，需达到此局数后可再被控制' },
    ]
  }
  resetDetails()
}

// 详情
const checkDetails = async (row: any) => {
  // 处理弹窗数据
  data.formParams = JSON.parse(JSON.stringify(row))
  data.formParams.rtp_control = JSON.parse(JSON.stringify(row.rtp_control))
  data.isShowDetails = true
}
// 选择触发周期
const chooseCycle = async (value: any) => {
  if (data.formParams.pigCycle > value || (data.formParams.pigCycle != 5 && value == 5)) {
    ElMessageBox.confirm('变更周期会将所有玩家记录数据清除，确认选择?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }).then(async () => {

    }).catch(() => {
      data.formParams.a_slots_pigCycle = data.formParams.pigCycle
    })
  }
}
// 修改保护配置
const editControl = throttle(async () => {
  indexStore.setModuleLoading(true)
  const parameter = JSON.parse(JSON.stringify(data.formParams))
  if (!parameter.a_slots_pigProfit || !parameter.a_slots_pigWater || !parameter.a_slots_pigNumber || !parameter.a_slots_pigInning) return ElMessage.error('请完善养客机制配置')
  // 保护配置
  let protect = parameter.rtp_num + '|' + parameter.beginner + ',' + parameter.nobeginner + '|' + parameter.rtp_check + '|' + BigTimeHundred(parameter.rtp_radio) + '|' + setStrControl(parameter.rtp_control);
  // 养客机制配置
  let a_slots_pig = parameter.a_slots_pigCycle + ',' + parameter.a_slots_pigWater + ',' + parameter.a_slots_pigProfit + ',' + parameter.a_slots_pigNumber + ',' + parameter.a_slots_pigInning;
  if (parameter.a_slots_pigCycle == 5) {
    parameter.time = new Time(parameter.date[0]).toTimestamp() + ',' + new Time(parameter.date[1]).toTimestamp()
    a_slots_pig = a_slots_pig + ',' + parameter.time
  }
  parameter.a_slots_protect = protect
  parameter.a_slots_pig = a_slots_pig
  indexStore.setModuleLoading(true)
  await editRTP(parameter)
  ElMessage.success('修改成功')
  onHideDetails(true)
},5000)
// 功能开关控制
const initialSynchronization = async () => {
  const parameter = JSON.parse(JSON.stringify(data.commercialForm))
  Object.assign(parameter, BatchControlRef.value.SetBatchControl())
  if(!parameter.agent_ids.length){
    return false
  }
  let message = `是否${data.commercialForm.a_slots_protectopen ? '开启' : '关闭'}控制？`;
  ElMessageBox.confirm(message, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    await editProtectOpen(parameter)
    ElMessage.success('同步成功')
    onHideDetails(true)
  }).catch(() => { })
}
// 获取养客默认配置
const getDefaultInfo = async () => {
  indexStore.setModuleLoading(true)
  let res = await getDefaultControl({});
  let slotsPig = setCommaToArr(res.data.a_slots_pig)
  data.formParams.a_slots_pigCycle = Number(slotsPig[0]) // 周期
  data.formParams.pigCycle = Number(slotsPig[0]) // 周期
  data.formParams.a_slots_pigWater = Number(slotsPig[1]) //流水倍数
  data.formParams.a_slots_pigProfit = Number(slotsPig[2]) //玩家净盈利
  data.formParams.a_slots_pigNumber = Number(slotsPig[3]) //生效次数
  data.formParams.a_slots_pigInning = Number(slotsPig[4]) //局数CD
  data.isShowUserControl = true
}
// 新增玩家控制
const setUserControl = throttle(async () => {
  const parameter = JSON.parse(JSON.stringify(data.formParams))
  Object.assign(parameter, BatchControlUserRef.value.SetBatchControlAlone())
  if(parameter.operated_id==-1 && !indexStore.is_general_agent){
    return ElMessage.error('请选择具体商户类别')
  }
  if(parameter.agent_id==-1){
    return ElMessage.error('请选择具体商户')
  }
  parameter.insert_type = 1
  if(!parameter.insert_values){
    return ElMessage.error('请输入平台ID')
  }
  // 养客机制配置
  if(!parameter.a_slots_pigWater || !parameter.a_slots_pigProfit || !parameter.a_slots_pigNumber || !parameter.a_slots_pigInning){
    return ElMessage.error('请完善养客机制配置')
  }
  let a_slots_pig = parameter.a_slots_pigCycle + ',' + parameter.a_slots_pigWater + ',' + parameter.a_slots_pigProfit + ',' + parameter.a_slots_pigNumber + ',' + parameter.a_slots_pigInning;
  if (parameter.a_slots_pigCycle == 5) {
    parameter.time = new Time(parameter.date[0]).toTimestamp() + ',' + new Time(parameter.date[1]).toTimestamp()
    a_slots_pig = a_slots_pig + ',' + parameter.time
  }
  parameter.a_slots_pig = a_slots_pig
  ElMessageBox.confirm('确认控制玩家使用养客配置？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    indexStore.setModuleLoading(true)
    await addUserControl(parameter)
    ElMessage.success('新增成功')
    onHideDetails(true)
  }).catch(() => { })
},5000)
// 删除玩家控制
const deleteUserControl = async (row:any) => {
  ElMessageBox.confirm(`确认解除玩家【${row.account3d_id}】${row.account3d}养客点控？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    await delUserControl({id:row.id})
    ElMessage.success('删除成功')
    onHideDetails(true)
  }).catch(() => {})
}
// 初始化RTP
const getInitializeRTP = async () => {
  ElMessageBox.confirm('是否初始化RTP', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    await initializeRTP({})
    ElMessage.success('初始化成功')
    onHideDetails(true)
  }).catch(() => { })
}
// 同步商户的RTP
const getSynchronizationRTP = async () => {
  const parameter = BatchControlRTPRef.value.SetBatchControl()
  ElMessageBox.confirm('是同步所选商户的RTP', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    await coverRTP({ agent_ids: parameter.agent_ids })
    ElMessage.success('同步成功')
    onHideDetails(true)
  }).catch(() => { })
}

// 保护配置
const addControl = () => {
  data.formParams.rtp_control.push({ gear: 0, drop: 0, pull: 0, beginner: 0, nobeginner: 0 })
}
const reduceControl = (index: number) => {
  if (!index && data.formParams.rtp_control.length == 1) {
    return ElMessage.error('最少保留一个配置！')
  }
  data.formParams.rtp_control.splice(index, 1)
}

// 调控配置
const setArrControl = (str: string, lowerMax: any, lowerMin: any, upperMax: any, upperMin: any) => {
  let arr = [], newArr: any[] = []
  arr = setSemicolonToArr(str)
  arr?.forEach((item: any, index: number) => {
    newArr.push({
      gear: Number(item[0]),
      drop: BigHundred(item[1]),
      pull: BigHundred(item[2]),
      beginner: BigHundred(item[3]),
      nobeginner: BigHundred(item[4]),
      lowerMax: BigHundred(lowerMax && lowerMax[index] ? lowerMax[index] : 0),
      lowerMin: BigHundred(lowerMin && lowerMin[index] ? lowerMin[index] : 0),
      upperMax: BigHundred(upperMax && upperMax[index] ? upperMax[index] : 0),
      upperMin: BigHundred(upperMin && upperMin[index] ? upperMin[index] : 0),
    })
  })
  return newArr
}
const setStrControl = (arr: any) => {
  arr?.forEach((item: any) => {
    item.drop = BigTimeHundred(item.drop)
    item.pull = BigTimeHundred(item.pull)
    item.beginner = BigTimeHundred(item.beginner)
    item.nobeginner = BigTimeHundred(item.nobeginner)
  })
  return setArrStr(arr)
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
}
const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}
// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const BatchControlRef = ref<any>()
const BatchControlRTPRef = ref<any>()
const BatchControlUserRef = ref<any>()
const onHideDetails = (show: boolean) => {
  data.dialogVisible = false
  data.isShowUserControl = false
  data.isShowDetails = false
  if (data.isShowCommercial) {
    BatchControlRef.value.onHideDetails()
  }
  data.isShowCommercial = false
  if (data.isShowRTP) {
    BatchControlRTPRef.value.onHideDetails()
  }
  data.isShowRTP = false
  if (show) {
    data.commercialForm = {
      agent_ids: [],
      game_ids: [],
      a_slots_protectopen: 0,
    }
    data.formParams = {
      rtp_num: 0,
      beginner: 0,
      nobeginner: 0,
      rtp_check: 0,
      rtp_radio: 0,
      rtp_control: [] as any[],
      a_slots_pigProfit: 0,
      a_slots_pigWater: 0,
      a_slots_pigNumber: 1,
      a_slots_pigCycle: 1,
      pigCycle: 0,
      a_slots_pigInning: 0,
      date: [],
      insert_values: ''
    } as any
    getSearchList()
  }
}
const OperatorRef = ref<any>()
const resetDetails = () => {
  data.query = {
    page: 1,
    size: 50,
    agent_id: -1,
    operated_id: -1,
    search_type: 1,
    search_value: '',
    date: getSevenWeek()
  }
  data.formParams = {
    rtp_num: 0,
    beginner: 0,
    nobeginner: 0,
    rtp_check: 0,
    rtp_radio: 0,
    rtp_control: [] as any[],
    a_slots_pigProfit: 0,
    a_slots_pigWater: 0,
    a_slots_pigNumber: 1,
    a_slots_pigCycle: 1,
    pigCycle: 0,
    a_slots_pigInning: 0,
    date: [],
    insert_values: ''
  } as any
  OperatorRef.value.onHideDetails()
  data.list = []
  data.total = 0
  getSearchList()
}
</script>

<style lang="scss" scoped>
.width500 {
  width: 850px;
  max-height: 300px;
  overflow: auto;
}

.marginB5 {
  width: 100%;
  padding-bottom: 2px;
  border-bottom: 1px solid #ededed;
}
</style>
